// pages/applyRepair/repairInfo.js
const app = getApp();
Page({
  data: {
    bgTextStyle: 'dark',
    scrollTop: '200rpx',
    bgColor: '#ff0000',
    bgColorTop: '#00ff00',
    bgColorBottom: '#0000ff',
    nbTitle: '维修信息',
    nbLoading: false,
    nbFrontColor: '#000000',
    nbBackgroundColor: '#ffffff',
    pageStyle: "color:#333333;background-color: #f1f1f1;",
    navs:[
      {title: "首页",class:"", path:"/pages/index/index", icon: "", font: "fa fa-home"},
      {title: "信息",class:"", path:"", icon: "", font: "fa fa-comments-o"},
      {title: "维修",class:"", path:"", icon: "", font: "fa fa-wrench"},
      {title: "我的",class:"co", path:"/pages/mine/mine", icon: "", font: "fa fa-user-circle"},
    ],
    orderInfo:{
      title: "",
      location: "",
      date: "",
      time: "",
      name: "",
      phone: "",
      images: [],
      mark: ""
    },
    binds: [],
    array: [],
    stars: [1,1,1,1,1],
    images: [{url:''},],
    index: 0,
    positions:[],
    comment: [],
    worker: [],
    logs: [],
    feedback: false,
    feedContent: '',
    feedImgs: [],
    status: 0,
    fix_id: 0,
    is_repeat: 0,
    position: 0,
    order_time: '',
    start: "2022-02-02",
    date: "2022-02-02",
    time: "09:00",
    order_id: 0,
    remark: "",
    type: 0,
    title: "",
    code: "",
    address: "",
    tel: "",
    bank: "",
    bank_code: "",
    name: "",
    phone: "",
    email: "",
    orderList:[],
    hasChange: false,
    enableRequest: true,
    ready: false
  },
  onLoad: function (options) {
  },
  onReady: function () {
  },
  onShow: function () {
    let v = this;
    let data = app.globalData.repairInfo;
    console.log("repairInfo",data);
    if (data) {
      let info = {};
      let imgs = data.imgs;
      info.title = data.content;
      info.position = data.positions;
      info.order_time = data.order_time;
      info.address = data.address;
      info.phone = data.phone;
      info.remark = data.remark;
      info.status = data.status;
      info.fix_id = data.fix_id;
      
      
      let images = [];
      let imga = imgs.split(',') || [];
      for(let k in imga)images.push({url: imga[k]});
      info.images = images;
      v.setData(info);
      let fix_id = data.fix_id;
      v.getComment(fix_id);
    }
  },
  getComment (fix_id) {
    let v = this;
    let url = app.globalData.host + '/api/fix/detail';
    wx.request({
      url: url, data: {fix_id:fix_id, token: app.globalData.token},
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          console.log("detail", r.data);
          let l = r.data.comment || [];
          let log = r.data.log || [];
          let status = r.data.status;
          let is_repeat = r.data.is_repeat;
          let w = r.data.worker || [];
          for(let i = 0; i < l.length; i++) {
            
            let imgs = l[i].imgs;
            let images = [];
            if (imgs && typeof imgs == 'string') images = imgs.split(',');
            l[i].star = parseInt(l[i].star) || 1;
            l[i].images = images;
          }
          let newData = {comment:l, logs: log, worker: w, status: status, is_repeat: is_repeat};
          if (r.data.feedback && r.data.feedback.fix_id) {
            let feedback = r.data.feedback;
            let feedImgs = [];
            let iis = feedback.imgs || '';
            if(typeof iis == 'string' && iis) feedImgs = iis.split(',');
            newData.feedback = true;
            newData.feedContent = feedback.content;
            newData.feedImgs = feedImgs;
          }
          console.log("newData",newData);
          v.setData(newData);
        }
      }
    })
  },
  getMyBinds: function() {
    let v = this;
    let token = app.globalData.token;
    if(!token) {
      app.afterLogin(v,v.getMyBinds);
      return;
    }
    let url = app.globalData.host + '/api/user/owner_list';
    wx.request({
      url: url, data: {token: app.globalData.token},
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          let l = r.data.list || [];
          let addrs = [];
          for(let k in l) {
            let addr = l[k].xiaoqu + l[k].addr;
            l[k].address = addr;
            addrs.push(addr);
          }
          console.log("getMyBinds",l);
          v.setData({binds: l,array: addrs});
          v.getPosition();
        }
      }
    })
  },
  getPosition() {
    let v = this;
    let url = app.globalData.host + '/api/common/fix_position';
    wx.request({
      url: url, data: {token: app.globalData.token},
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          let l = r.data || [];
          console.log("position",l);
          v.setData({positions: l});
        }
      }
    })
  },
  bindDateChange(ev){
    this.setData({date: (ev.detail.value) || 0});
  },
  bindTimeChange(ev){
    this.setData({time: (ev.detail.value) || 0});
  },
  bindPosChange(ev){
    this.setData({position: (ev.detail.value) || 0});
  },
  bindKeyInput(ev){
    this.setData({title: ev.detail.value});
  },
  bindKeyInputPos(ev){
    this.setData({location: ev.detail.value});
  },
  bindPickerChange: function(ev) {
    this.setData({ index: ev.detail.value })
  },
  bindKeyInputName(ev){
    this.setData({name: ev.detail.value});
  },
  bindKeyInputPhone(ev){
    this.setData({phone: ev.detail.value});
  },
  bindKeyInputRemark(ev){
    this.setData({remark: ev.detail.value});
  },
  doRequestTicket(ev) {
    let v = this;
    wx.showModal({
      title: '维修完成',
      content: '是否确认维修完成？',
      success (res) {
        console.log(res)
        if (res.confirm) {
          v.doRequestEndSub();
        }
      }
    });
  },
  doRequestEndSub(ev){
    let v = this;
    console.log("doRequestEndSub");
    let url = app.globalData.host + '/api/fix/status';
    let data = {status: 3, fix_id: v.data.fix_id, token: app.globalData.token};
    wx.request({
      url: url, data: data,
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          wx.showToast({ title: r.msg || '提交成功',icon:'none'})
          v.setData({enableRequest: false});
          wx.navigateBack({ delta: 1,  });
        } else {
          wx.showToast({ title: r.msg || '提交失败',icon:'none'})
        }
      }
    })
  },
  doRequestFail() {
    let v = this;
    if (1) {
      wx.navigateTo({url: '/pages/applyRepair/failInfo'});
      return;
    }
    wx.showModal({
      title: '维修反馈',
      content: '确认未解决问题？',
      success (res) {
        console.log(res)
        if (res.confirm) {
          v.doRequestFailSub();
        }
      }
    });
  },
  doRequestFailSub() {
    let v = this;
    console.log("doRequestFailSub");
    let url = app.globalData.host + '/api/fix/status';
    let data = {status: -1, fix_id: v.data.fix_id, token: app.globalData.token};
    wx.request({
      url: url, data: data,
      success (res) {
        let r = res.data;
        if(r.code == 200 && r.data) {
          wx.showToast({ title: r.msg || '提交成功',icon:'none'})
          v.setData({enableRequest: false});
          wx.navigateBack({ delta: 1,  });
        } else {
          wx.showToast({ title: r.msg || '提交失败',icon:'none'})
        }
      }
    })
  },
  uploadAvator(ev) {
    const v = this;
    console.log("uploadAvator",ev);
    let index = 0;
    let ds = ev.target.dataset;
    if (ds) index = parseInt(ds.index) || 0;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        const size = res.tempFiles[0].size;
        const name = v.getRandFileName(tempFilePath);
        console.log(name,res);
        const url = app.globalData.host + "/api/common/upimg";
        wx.uploadFile({
          url: url, //仅为示例，非真实的接口地址
          filePath: tempFilePath,
          name: 'file',
          formData: {'user': v.data.uid },
          success (res){
            let data = res.data
            if(typeof data == 'string') data = JSON.parse(data);
            console.log(data,res);
            let images = v.data.images;
            if (data.code == 200) {
              let src = data.data.src;
              images[index].url = src;
              v.setData({images: images});
            }
          },
          fail (err) {
            console.log("fail", err);
          }
        })
      }
    })
  },
  previewImage(ev) {
    const v = this;
    console.log("previewImage",ev);
    let index = 0;
    let ds = ev.target.dataset;
    if (ds) index = parseInt(ds.index) || 0;
    
    let images = v.data.images;
    if (!images[index] || !images[index].url) return;
    let l = [];
    for (let k in images) if(images[k].url) l.push(images[k].url);
    wx.previewImage({ current: l[index], urls: l });
  },
  previewCommentImage(ev) {
    const v = this;
    let i = 0;
    let k = 0;
    let ds = ev.target.dataset;
    if (ds) i = parseInt(ds.i) || 0;
    if (ds) k = parseInt(ds.k) || 0;
    let comment = v.data.comment;
    console.log("previewCommentImage",i,k,comment);
    let images = comment[i].images || [];
    wx.previewImage({ current: images[k], urls: images });
  },
  getRandFileName(filePath) {
    let v = this;
    const extIndex = filePath.lastIndexOf('.');
    const extName = extIndex === -1 ? '' : filePath.substr(extIndex);
    let rname = parseInt(`${Date.now()}${Math.floor(Math.random() * 900 + 100)}`, 10).toString(36);
    let saveName = rname + extName;
    if(v.data.uid) {
      saveName = "" + v.data.uid + extName;
    }
    return saveName;
  },
  onSuccess: function (res) {
    console.log(res.detail);
  },
  onFail: function (res) {
    console.log(res);
  },
  onHide: function () {
  },
  onUnload: function () {
  },
  onPullDownRefresh: function () {
  },
  onReachBottom: function () {
  },
  onShareAppMessage: function () {
  }
})